import json

from django.core import serializers
from django.http import HttpResponse, JsonResponse
from requests import Response, request
from rest_framework.generics import ListAPIView, RetrieveAPIView, GenericAPIView
from rest_framework.mixins import RetrieveModelMixin
from rest_framework.views import APIView
from rest_framework.viewsets import ReadOnlyModelViewSet

from spitslot.serializer import CommentSeriazlier
from .models import Tsukkomi_Details, Comment
from . import serializer


# url('^spitslot/$',views.UserView.as_view()), 首页
class UserView(ListAPIView):
    serializer_class = serializer.TsukkomiListSeriazlier
    queryset = Tsukkomi_Details.objects.all().order_by('-datetime')


# url('^spitslot/(?P<pk>\d+)$',views.Tsukkomi_Details_view.as_view())  详情
class Tsukkomi_Details_view(RetrieveModelMixin, GenericAPIView):
    queryset = Tsukkomi_Details.objects.all()
    serializer_class = serializer.TsukkomiListSeriazlier

    def get(self, request, pk):
        return self.retrieve(request, pk)


# url('^comment_view/$',views.comment_view.as_view())  吐槽评论
class comment_view(ListAPIView):
    # serializer_class = serializer.CommentSeriazlier
    def get(self, request):  # 获取评论
        data = request.GET
        queryset = Comment.objects.filter(Tsukkomi_id_id=data['id'], parent_id=None).order_by('-create_time')
        data = serializers.serialize('json', queryset)
        data = json.loads(data)
        for i in data:
            print(i['pk'])
            print(i["fields"]["parent_id"])
            tt = Comment.objects.filter(Tsukkomi_id="1", parent_id=i['pk']).order_by('-create_time')
            tt = serializers.serialize('json', tt)
            tt = json.loads(tt)
            i["ttt"] = []
            i["ttt"] += tt
        return JsonResponse(data, safe=False)

    def post(self, request):  # 发表评论
        data = request.data
        Comment.objects.create(user_id=data['user_id'], content=data['content'],
                               Tsukkomi_id_id=data['Tsukkomi_id'])
        # print(book_obj1)
        return HttpResponse("ok")


#
# # url('^commentReply_view/(?P<pk>\d+)$',views.reply_view.as_view())   评论回复
class commentReply_view(ListAPIView):

    def post(self, request):
        data = request.data
        Comment.objects.create(user_id=data['user_id'], Tsukkomi_id_id=data['Tsukkomi_id'], content=data['content'],
                               parent_id=data['parent_id'])
        return HttpResponse('ok')


# 发布吐槽
class publish_tsukkomi_view(ListAPIView):

    def post(self, request):
        print(request.data)
        data = request.data
        Tsukkomi_Details.objects.create(user_id=data['user_id'], username=data['username'], datetime=data['datatime'],
                                        publishs=data['publishs'])
        return HttpResponse("ok")


# url('^comment_view/$',views.comment_view.as_view())  吐槽评论
class comment_view(ListAPIView):
    # serializer_class = serializer.CommentSeriazlier
    def get(self, request):  # 获取评论
        data = request.GET
        queryset = Comment.objects.filter(Tsukkomi_id_id=data['id'], parent_id=None).order_by('-create_time')
        data = serializers.serialize('json', queryset)
        data = json.loads(data)
        for i in data:
            print(i['pk'])
            print(i["fields"]["parent_id"])
            tt = Comment.objects.filter(Tsukkomi_id="1", parent_id=i['pk']).order_by('-create_time')
            tt = serializers.serialize('json', tt)
            tt = json.loads(tt)
            i["ttt"] = []
            i["ttt"] += tt
        return JsonResponse(data, safe=False)

    def post(self, request):  # 发表评论
        data = request.data
        Comment.objects.create(user_id=data['user_id'], content=data['content'],
                               Tsukkomi_id_id=data['Tsukkomi_id'])
        # print(book_obj1)
        return HttpResponse("ok")


#
# # url('^commentReply_view/(?P<pk>\d+)$',views.reply_view.as_view())   评论回复
class commentReply_view(ListAPIView):

    def post(self, request):
        data = request.data
        Comment.objects.create(user_id=data['user_id'], Tsukkomi_id_id=data['Tsukkomi_id'], content=data['content'],
                               parent_id=data['parent_id'])
        return HttpResponse('ok')



class Spit_like(GenericAPIView, ListModelMixin):
    """吐槽点赞"""

    serializer_class = SpitLikeSerializer

    def get_queryset(self):
        user_id = self.request.query_params.get('user_id')
        return SpitLike.objects.filter(user_id=user_id)

    def get(self, request):
        spitset = self.get_queryset()
        serializer = self.get_serializer(spitset, many=True)
        # spit_likes = []
        # for spit_like in serializer.data:
        #     print(spit_like)
        #     spit_likes.append(spit_like['spit_id'])

        # return Response({'spit_likes': spit_likes})
        return Response(serializer.data)


class SpitLikeActionView(APIView):
    """吐槽点赞与取消点赞"""
    permission_classes = [IsAuthenticated]

    def post(self, request):
        user = request.user
        serializer = SpitLikeActionSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        spit_id = serializer.validated_data['comment_id']
        action = serializer.validated_data['action']
        # print(spit_id.like_count)
        instance = CommentLike.objects.filter(user_id=user, spit_id=spit_id)
        if action == 'add':
            with transaction.atomic():
                try:
                    save_id = transaction.savepoint()
                    spit_like = CommentLike.objects.create(
                        user_id=user,
                        spit_id=spit_id
                    )
                    spit_like.save()
                    spit_id.like_count += 1
                    spit_id.save()
                except Exception:
                    transaction.savepoint_rollback(save_id)
                    raise
                else:
                    transaction.savepoint_commit(save_id)
        else:
            instance.delete()
            spit_id.like_count -= 1
            spit_id.save()

        return Response({'message': "ok"})








# 发布吐槽
class publish_tsukkomi_view(ListAPIView):

    def post(self, request):
        print(request.data)
        data = request.data
        Tsukkomi_Details.objects.create(user_id=data['user_id'], username=data['username'], datetime=data['datatime'],
                                        publishs=data['publishs'])
        return HttpResponse("ok")






